package cn.ac.cintcm.webapp.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.MessageSource;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import cn.ac.cintcm.Constants;
import cn.ac.cintcm.model.User;
import cn.ac.cintcm.service.FeedbackManager;
import cn.ac.cintcm.service.RoleManager;
import cn.ac.cintcm.service.UserManager;

public class MainMenuController extends MultiActionController {

	private FeedbackManager fm;
	private MessageSource messageSource;
	private String view;
	private UserManager um;
	//private transient final Log log = LogFactory.getLog(MainMenuController.class);
	private RoleManager rm;
	
	public void setFeedBackManager(FeedbackManager fm) {
		this.fm = fm;
	}
	
	public void setUserManager(UserManager um) {
		this.um = um;
	}
	
	public void setRoleManager(RoleManager rm) {
		this.rm = rm;
	}
	
	public void setSuccessView(String view) {
		this.view = view;
	}
	
    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }
    
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = null;
		
		String username = request.getRemoteUser();
		User user = um.getUserByUsername(username);
		String userId = user.getId() + "";
		
		if (!user.getRoles().contains(rm.getRole(Constants.DOCTOR_ROLE))) {
			mv = new ModelAndView("redirect:patient.html?f=m&u=" + user.getId());
		} else {
			mv = new ModelAndView(view);
			int unread = fm.getUnreadCount(userId);
			int effective = fm.getEffectiveCount(userId);
			int ineffective = fm.getProblematicCount(userId);
			MessageSourceAccessor text = new MessageSourceAccessor(messageSource, request.getLocale());
			String statics = unread > 0 ? text.getMessage("feedBack.statics", 
					new Object[] {unread, effective, ineffective}) : "";
			mv.addObject("statics", statics);
			
			mv.addObject("feedbacks",fm.getUnread(username));

			int attentionUserCount = um.getAttentionUserCount(username);
			String care = attentionUserCount > 0 ? text.getMessage("user.care",  new Object[] {attentionUserCount}) : "";
			mv.addObject("care", care);
			
			mv.addObject("recent", um.getRecentUser(username));
			System.out.println("leaving main controller...");
		}
		
		return mv;
	}

}
